from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models

from itsdangerous import TimedJSONWebSignatureSerializer as Ser, BadData

# Create your models here.
from . import constants


class User(AbstractUser):
    """用户模型类"""
    # 如果要验证邮箱唯一。则需要重写邮箱字段
    # email = models.EmailField(_('email address'), blank=True,null=True,unique=True)

    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')
    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')  # 为True时表示用户已验证通过
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE,related_name='follwed', verbose_name='用户关注')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name
#
#     # def generate_verify_email_url(self):
#     #     """
#     #     生成验证邮箱的url
#     #     """
#     #     # 将连接用itsdangerous加密 生成对象
#     #     serializer = Ser(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
#     #     # 组织数据，将userid 和 email都封装进加密数据里
#     #     data = {'user_id': self.id, 'email': self.email}
#     #     # 进行加密 加密之后是byte类型 。decode进行转码
#     #     token = serializer.dumps(data).decode()
#     #     # 拼接路径
#     #     verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
#     #     return verify_url
#     #
#     # @staticmethod
#     # def check_verify_email_token(token):
#     #     # 将连接用itsdangerous解密 生成对象
#     #     serializer = Ser(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES)
#     #     # 对数据进行验证
#     #     try:
#     #         data = serializer.loads(token)
#     #     except BadData:
#     #         return None
#     #     # 查询数据库 如果可以查询出来 表示用户存在 返回user
#     #     try:
#     #         user_id = data.get('user_id')
#     #         email = data.get('email')
#     #
#     #         user = User.objects.get(id=user_id, email=email)
#     #     # 如果用户不存在 返回None
#     #     except Exception:
#     #         return None
#     #     else:
#     #         return user
